package morning.cat.springbootdemo.controller;

import com.google.common.collect.Maps;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import morning.cat.springbootdemo.entity.User;
import org.springframework.web.bind.annotation.*;

import java.util.Collection;
import java.util.Map;

@RestController
@RequestMapping(value = "/api/v1.0")
@Api(value = "用户管理开放API 版本1.0")
public class UserController {

    public static Map<Integer, User> DATA = Maps.newHashMap();

    @ApiOperation(value = "获取用户详细信息", notes = "根据url的id来获取用户详细信息")
    @ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Integer", paramType = "path")
    @GetMapping("/user/{id}")
    public User getUserById(@PathVariable("id") Integer id) {
        User user = DATA.get(id);
        if (user == null) {
            user = new User(0, "moringcat");
        }
        return user;
    }

    @GetMapping("/users")
    @ApiOperation(value = "获取所有用户")
    public Collection<User> getAllUser() {
        return DATA.values();
    }

    @ApiOperation(value = "创建用户", notes = "根据User对象创建用户")
    @ApiImplicitParam(name = "user", value = "用户详细实体user", required = true, dataType = "User")
    @PostMapping("/user")
    //@RequestParam Integer id, @RequestParam String name
    public User addUser(@RequestBody User user) {
        //User user = new User(id, name);
        DATA.put(user.getId(), user);
        return user;
    }

    @ApiOperation(value = "删除用户", notes = "根据url的id来删除用户")
    @ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Integer", paramType = "path")
    @DeleteMapping("/user/{id}")
    public User delUserById(@PathVariable("id") Integer id) {
        User user = DATA.get(id);
        if (id != null) {
            DATA.remove(id);
        }
        return user;
    }

    @ApiOperation(value = "更新用户详细信息", notes = "根据url的id来更新用户详细信息")
    @ApiImplicitParams({@ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Integer", paramType = "path"),
            @ApiImplicitParam(name = "name", value = "用户姓名", required = true, dataType = "String", paramType = "path")})
    @PutMapping("/user")
    public User updateUser(@RequestParam Integer id, @RequestParam String name) {
        User user = new User(id, name);
        DATA.put(id, user);
        return user;
    }
}
